#cookies失效时获取新的cookies
import re

import requests
import json

from retrying import retry

import cookies_pool


@retry(stop_max_attempt_number=3, wait_fixed=1000)
def get_new_skey():
    headers = {
        "authority": "weread.qq.com",
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/json;charset=UTF-8",
        "origin": "https://weread.qq.com",
        "referer": "https://weread.qq.com/web/reader/be832770813ab6b8eg01004a?",
        "sec-ch-ua": "\"Chromium\";v=\"116\", \"Not)A;Brand\";v=\"24\", \"Google Chrome\";v=\"116\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Linux\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
    }
    cookies = cookies_pool.cookies
    url = "https://weread.qq.com/web/login/renewal"
    data = {
        "rq": "%2Fweb%2Fbook%2Fread"
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=cookies, data=data)

    set_cookies=response.headers['Set-Cookie']
    pattern = r'wr_skey=(.*?);'
    match = re.search(pattern, set_cookies)
    if match:
        skey = match.group(1)
        print(skey)  # 输出：6QxTxvmJ
        # return skey
        return skey
        # change_cookies(skey)

